package top.zywork.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import top.zywork.annotation.AppAuthFilter;
import top.zywork.annotation.SysLog;
import top.zywork.common.*;
import top.zywork.constant.CommonConstant;
import top.zywork.constant.FileConstants;
import top.zywork.dos.UserCertificationDO;
import top.zywork.dto.PagerDTO;
import top.zywork.dto.UserCertificationDTO;
import top.zywork.enums.CertificationCheckStatusEnum;
import top.zywork.enums.CertificationTypeEnum;
import top.zywork.enums.DatePatternEnum;
import top.zywork.enums.UploadTypeEnum;
import top.zywork.query.UserCertificationQuery;
import top.zywork.security.SecurityUtils;
import top.zywork.service.UploadService;
import top.zywork.service.UserCertificationService;
import top.zywork.vo.PagerVO;
import top.zywork.vo.ResponseStatusVO;
import top.zywork.vo.UserCertificationNotThroughVO;
import top.zywork.vo.UserCertificationVO;
import top.zywork.vo.wx.UserCertificationCheckVO;
import top.zywork.wx.save.UserCertificationSave;
import top.zywork.wx.update.UserCertificationUpdate;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户实名认证表 前端控制器
 * </p>
 *
 * @author
 * @since 2020-10-18
 */
@RestController
@RequestMapping("/user-certification")
@AppAuthFilter(ignoreUrls = {
        "/user-certification/user/upload-img"
})
public class UserCertificationController {

    @Value("${storage.provider}")
    private String storageProvider;

    @Value("${storage.local.compressSizes}")
    private String compressSizes;

    @Value("${storage.local.compressScales}")
    private String compressScales;

    @Value("${storage.local.userCertification.imgParentDir}")
    private String imgParentDir;

    @Value("${storage.local.userCertification.imgDir}")
    private String imgDir;

    @Value("${storage.local.userCertification.imgUrl}")
    private String imgUrl;

    @Value("${storage.local.userCertification.keepFileName}")
    private Boolean keepFileName;

    private UserCertificationService userCertificationService;

    private UploadService uploadService;

    /**
     * 用户认证保存
     * @return
     */
    @PostMapping("user/save")
    public ResponseStatusVO save(@RequestBody UserCertificationSave userCertificationSave, BindingResult bindingResult){
        if (bindingResult.hasErrors()) {
            return ResponseStatusVO.dataError(BindingResultUtils.errorString(bindingResult), null);
        }
        return userCertificationService.save(userCertificationSave);
    }

    /**
     * 用户认证编辑
     */
    @PostMapping("user/update")
    public ResponseStatusVO update(@RequestBody UserCertificationUpdate userCertificationUpdate, BindingResult bindingResult){
        if (bindingResult.hasErrors()) {
            return ResponseStatusVO.dataError(BindingResultUtils.errorString(bindingResult), null);
        }

        return userCertificationService.update(userCertificationUpdate);
    }


    /**
     * 检查用户认证状态
     * @return
     */
    @GetMapping("user/check")
    public ResponseStatusVO check(){
        long userId = SecurityUtils.getJwtUser().getUserId();
        UserCertificationDO result = userCertificationService.getOne(new QueryWrapper<UserCertificationDO>().eq("user_id", userId));
        UserCertificationCheckVO userCertificationCheckVO = new UserCertificationCheckVO();
        if(result==null){
            userCertificationCheckVO.setFlag(Boolean.FALSE);
        }else{
            userCertificationCheckVO.setFlag(Boolean.TRUE);
            userCertificationCheckVO.setCode(result.getCheckStatus());
            userCertificationCheckVO.setCodeDes(CertificationCheckStatusEnum.getEnum(result.getCheckStatus()).getValue());
            // 只要不是认证成功都可以返回ID 以便进行修改 认证中、认证失败
            if(!result.getCheckStatus().equals(CertificationCheckStatusEnum.AUTHENTICATION_FAILED.getCode())){
                userCertificationCheckVO.setId(result.getId());
                userCertificationCheckVO.setCheckDes(result.getCheckDes());
            }
        }
        return ResponseStatusVO.ok("查询成功",userCertificationCheckVO);
    }

    /**
     * 查询认证失败用户认证信息
     * @return
     */
    @GetMapping("user/info/{id}")
    public ResponseStatusVO info(@PathVariable("id") Long id){
        return ResponseStatusVO.ok("查询成功",userCertificationService.info(id));
    }

    /**
     * 后台通过骑手认证
     * @param id
     * @return
     */
    @PostMapping("admin/through/{id}")
    @SysLog(description = "后台通过骑手认证")
    public ResponseStatusVO through(@PathVariable("id") Long id){
        UserCertificationDO byId = userCertificationService.getById(id);
        if(byId == null){
            return ResponseStatusVO.error("审核数据不存在！",null);
        }
        byId.setCheckStatus(CertificationCheckStatusEnum.AUTHENTICATION_FAILED.getCode());
        userCertificationService.updateById(byId);
        return ResponseStatusVO.ok("操作成功",null);
    }


    /**
     * 后台不通过骑手认证审核
     * @return
     */
    @PostMapping("admin/notThrough")
    @SysLog(description = "后台不通过骑手认证")
    public ResponseStatusVO notThrough(@RequestBody UserCertificationNotThroughVO  userCertificationNotThroughVO){
        UserCertificationDO byId = userCertificationService.getById(userCertificationNotThroughVO.getId());
        if(byId == null){
            return ResponseStatusVO.error("审核数据不存在！",null);
        }
        byId.setCheckStatus(CertificationCheckStatusEnum.CERTIFIED.getCode());
        if(StringUtils.isBlank(userCertificationNotThroughVO.getCheckDes())){
            userCertificationNotThroughVO.setCheckDes("审核失败，请重新提交。");
        }
        byId.setCheckDes(userCertificationNotThroughVO.getCheckDes());
        userCertificationService.updateById(byId);
        return ResponseStatusVO.ok("操作成功",null);
    }

    /**
     * 上传一卡通，学生证图片
     * @param file
     * @return
     */
    @PostMapping("user/upload-img")
    @SysLog(description = "后台上传用户头像", requestParams = false)
    public ResponseStatusVO uploadHeadicon(MultipartFile file) {
        String date = DateFormatUtils.format(DateUtils.currentDate(), DatePatternEnum.DATE.getValue());
        UploadUtils.UploadOptions uploadOptions = UploadUtils.UploadOptions.builder().uploadParentDir(imgParentDir).uploadDir(imgDir + FileConstants.SEPARATOR + date)
                .dbSaveUrl(imgUrl + FileConstants.SEPARATOR + date).keepFileName(keepFileName).build();
        ResponseStatusVO responseStatusVO = uploadService.uploadFile(storageProvider, file, UploadTypeEnum.IMAGE.getAllowedExts(), UploadTypeEnum.IMAGE.getMaxSize(), uploadOptions);
        return responseStatusVO;
    }


    @PostMapping("admin/save")
    @SysLog(description = "后台保存UserCertificationVO")
    public ResponseStatusVO save(@RequestBody @Validated UserCertificationVO userCertificationVO, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResponseStatusVO.dataError(BindingResultUtils.errorString(bindingResult), null);
        }
        UserCertificationDO copy = BeanUtils.copy(userCertificationVO, UserCertificationDO.class);
        copy.setIsActive(CommonConstant.IS_ACTIVE_TRUE);
        copy.setCreateTime(new Date());
        copy.setUpdateTime(new Date());
        userCertificationService.save(copy);
        return ResponseStatusVO.ok("添加成功", null);
    }


    @GetMapping("admin/remove/{id}")
    @SysLog(description = "后台删除UserCertificationVO")
    public ResponseStatusVO removeById(@PathVariable("id") Long id) {
        userCertificationService.removeById(id);
        return ResponseStatusVO.ok("删除成功", null);
    }


    @PostMapping("admin/update")
    @SysLog(description = "后台更新UserCertificationVO")
    public ResponseStatusVO update(@RequestBody @Validated UserCertificationVO userCertificationVO, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResponseStatusVO.dataError(BindingResultUtils.errorString(bindingResult), null);
        }
        UserCertificationDO copy = BeanUtils.copy(userCertificationVO, UserCertificationDO.class);
        copy.setUpdateTime(new Date());
        boolean result = userCertificationService.updateById(copy);
        if (result) {
            return ResponseStatusVO.ok("更新成功", null);
        } else {
            return ResponseStatusVO.dataError("数据版本号有问题，在此更新前数据已被更新", null);
        }
    }

    @GetMapping("admin/one/{id}")
    public ResponseStatusVO getById(@PathVariable("id") Long id) {
        UserCertificationVO userCertificationVO = new UserCertificationVO();
        Object obj = userCertificationService.getById(id);
        if (obj != null) {
            userCertificationVO = BeanUtils.copy(obj, UserCertificationVO.class);
        }
        return ResponseStatusVO.ok("查询成功", userCertificationVO);
    }

    @GetMapping("admin/all")
    public ResponseStatusVO listAll() {
        IPage page = userCertificationService.page(null);
        PagerDTO pagerDTO = PagerDTO.builder().total(page.getTotal()).rows(page.getRecords()).build();
        PagerVO pagerVO = BeanUtils.copy(pagerDTO, PagerVO.class);
        pagerVO.setRows(BeanUtils.copyList(pagerDTO.getRows(), UserCertificationDTO.class));
        return ResponseStatusVO.ok("查询成功", pagerVO);
    }

    @PostMapping("admin/all-cond")
    public ResponseStatusVO listAllByCondition(@RequestBody UserCertificationQuery userCertificationQuery) {
        PagerDTO pagerDTO = userCertificationService.listAllByCondition(userCertificationQuery);
        PagerVO pagerVO = BeanUtils.copy(pagerDTO, PagerVO.class);
        pagerVO.setRows(BeanUtils.copyList(pagerDTO.getRows(), UserCertificationVO.class));
        return ResponseStatusVO.ok("查询成功", pagerVO);
    }

    @PostMapping("admin/pager-cond")
    public ResponseStatusVO listPageByCondition(@RequestBody UserCertificationQuery userCertificationQuery) {
        PagerDTO pagerDTO = userCertificationService.listPageByCondition(userCertificationQuery);
        PagerVO pagerVO = BeanUtils.copy(pagerDTO, PagerVO.class);
        List<Object> collect = pagerDTO.getRows().stream().map(e -> {
            UserCertificationDO userCertificationDO = (UserCertificationDO) e;
            UserCertificationVO userCertificationVO = new UserCertificationVO();
            org.springframework.beans.BeanUtils.copyProperties(userCertificationDO, userCertificationVO);
            userCertificationVO.setCheckStatusValue(CertificationCheckStatusEnum.getEnum(userCertificationDO.getCheckStatus()).getValue());
            return userCertificationVO;
        }).collect(Collectors.toList());
        pagerVO.setRows(collect);
        return ResponseStatusVO.ok("查询成功", pagerVO);
    }

    @Autowired
    public void setUploadService(UploadService uploadService) {
        this.uploadService = uploadService;
    }

    @Autowired
    public void setUserCertificationService(UserCertificationService userCertificationService) {
        this.userCertificationService = userCertificationService;
    }
}
